package com.luaj.elasticsearch.common.exception;

import com.luaj.elasticsearch.common.enums.EmBusinessError;
import com.luaj.elasticsearch.common.model.CommonError;
import com.luaj.elasticsearch.common.model.CommonRes;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 卢安杰
 * @date 2020-11-20 19:39
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest request, HttpServletResponse response,Exception ex){
        ex.printStackTrace();
        if(ex instanceof BusinessException){
            return CommonRes.fail(((BusinessException)ex).getCommonError());
        }else if(ex instanceof ServletRequestBindingException){
            return CommonRes.fail(CommonError.error(EmBusinessError.REQUEST_BIND_ERROR));
        }else if(ex instanceof NoHandlerFoundException){
            return CommonRes.fail(CommonError.error(EmBusinessError.URL_NOT_FOUND));
        }else{
            return CommonRes.fail(CommonError.error(EmBusinessError.UNKOWN_EARROR));
        }
    }
}
